/**
 * API服务 - 处理与后端的所有API调用
 */

// API基础URL
const API_BASE_URL = 'http://localhost:8080/api';

/**
 * 通用API请求函数
 * @param {string} endpoint - API端点
 * @param {string} method - HTTP方法 (GET, POST, PUT, DELETE)
 * @param {Object} data - 请求数据 (可选)
 * @returns {Promise} - 返回Promise对象
 */
async function apiRequest(endpoint, method = 'GET', data = null) {
    const url = `${API_BASE_URL}${endpoint}`;

    const options = {
        method,
        headers: {
            'Content-Type': 'application/json',
            'Accept': 'application/json'
        },
        credentials: 'include' // 包含cookies
    };

    if (data) {
        options.body = JSON.stringify(data);
    }

    try {
        const response = await fetch(url, options);

        // 检查响应状态
        if (!response.ok) {
            const errorData = await response.json().catch(() => ({}));
            throw new Error(errorData.message || `请求失败: ${response.status}`);
        }

        // 检查是否有响应内容
        const contentType = response.headers.get('content-type');
        if (contentType && contentType.includes('application/json')) {
            return await response.json();
        }

        return {};
    } catch (error) {
        console.error('API请求错误:', error);
        throw error;
    }
}

/**
 * 用户相关API
 */
const userApi = {
    // 用户注册
    register: (userData) => apiRequest('/users/register', 'POST', userData),

    // 用户登录
    login: (credentials) => apiRequest('/users/login', 'POST', credentials),

    // 获取用户信息
    getUserInfo: (userId) => apiRequest(`/users/${userId}`),

    // 更新用户信息
    updateUserInfo: (userId, userData) => apiRequest(`/users/${userId}`, 'PUT', userData)
};

/**
 * 健康档案相关API
 */
const healthProfileApi = {
    // 获取用户健康档案
    getHealthProfile: (userId) => apiRequest(`/users/${userId}/health-profile`),

    // 创建或更新健康档案
    saveHealthProfile: (userId, profileData) => apiRequest(`/users/${userId}/health-profile`, 'POST', profileData),

    // 计算BMI
    calculateBMI: (userId) => apiRequest(`/users/${userId}/bmi`),

    // 计算基础代谢率
    calculateBMR: (userId) => apiRequest(`/users/${userId}/bmr`),

    // 获取营养需求
    getNutritionNeeds: (userId) => apiRequest(`/users/${userId}/nutrition-needs`)
};

/**
 * 食品分析相关API
 */
const foodAnalysisApi = {
    // 获取所有食品
    getAllFoods: () => apiRequest('/food-items'),

    // 获取食品详情
    getFoodDetails: (foodId) => apiRequest(`/food-items/${foodId}`),

    // 上传食品图片进行分析
    analyzeFood: (formData) => {
        const url = `${API_BASE_URL}/food-items/analyze-image`;
        return fetch(url, {
            method: 'POST',
            body: formData,
            credentials: 'include'
        }).then(response => {
            if (!response.ok) {
                throw new Error(`请求失败: ${response.status}`);
            }
            return response.json();
        });
    },

    // 搜索食品
    searchFoods: (query) => apiRequest(`/food-items/search?q=${encodeURIComponent(query)}`)
};

/**
 * 饮食记录相关API
 */
const dietRecordApi = {
    // 获取用户的饮食记录
    getUserDietRecords: (userId) => apiRequest(`/users/${userId}/diet-records`),

    // 添加饮食记录
    addDietRecord: (userId, recordData) => apiRequest(`/users/${userId}/diet-records`, 'POST', recordData),

    // 更新饮食记录
    updateDietRecord: (recordId, recordData) => apiRequest(`/users/${userId}/diet-records/${recordId}`, 'PUT', recordData),

    // 删除饮食记录
    deleteDietRecord: (recordId) => apiRequest(`/users/${userId}/diet-records/${recordId}`, 'DELETE')
};

// 导出API服务
window.apiService = {
    user: userApi,
    healthProfile: healthProfileApi,
    foodAnalysis: foodAnalysisApi,
    dietRecord: dietRecordApi
};